/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.web.editors.workbench;

import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.uploadHist.GetUploadHistCmd;
import cn.easyplatform.studio.cmd.uploadHist.SetUploadHistCmd;
import cn.easyplatform.studio.context.Contexts;
import cn.easyplatform.studio.utils.*;
import cn.easyplatform.studio.vos.MediaFileVo;
import cn.easyplatform.studio.vos.UploadHistVo;
import cn.easyplatform.studio.web.editors.AbstractPanelEditor;
import cn.easyplatform.studio.web.editors.ComponentCallback;
import cn.easyplatform.studio.web.layout.WorkbenchController;
import cn.easyplatform.studio.web.views.impl.AbstractView;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.ReaderInputStream;
import org.zkoss.image.AImage;
import org.zkoss.util.media.AMedia;
import org.zkoss.util.media.Media;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.*;
import org.zkoss.zkmax.zul.Dropupload;
import org.zkoss.zul.*;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.util.Arrays;
import java.util.List;

public class FileEditor extends AbstractPanelEditor {

    BASE64Encoder encoder = new BASE64Encoder();//编码

    BASE64Decoder decoder = new BASE64Decoder();//解码


    private Div center;

    private Tabbox tabbox;

    private Iframe iframe_audio;

    private Iframe iframe_video;

    private Button upload_img;

    private Button upload_audio;

    private Button upload_video;

    private Button upload_css;

    private Button upload_js;

    private Button btnImgHist;

    private Button btnImgHistRef;

    private Button btnImgRevert;

    private Button btnCssHist;

    private Button btnCssHistRef;

    private Button btnCssRevert;

    private Button btnJsHist;

    private Button btnJsHistRef;

    private Button btnJsRevert;

    private Button btnAudioHist;

    private Button btnAudioHistRef;

    private Button btnAudioRevert;

    private Button btnVideoHist;

    private Button btnVideoHistRef;

    private Button btnVideoRevert;

    private Listbox audioListbox;

    private Listbox videoListbox;

    private Listbox cssListbox;

    private Listbox jsListbox;

    private Listbox imgHistory;

    private Listbox cssHistory;

    private Listbox jsHistory;

    private Listbox audioHistory;

    private Listbox videoHistory;

    private Image pics;

    private Menupopup menu;

    private Div imgFrame;

    private Image preView;

    private Component selectComp;

    private South imgSouth;

    private South cssSouth;

    private South jsSouth;

    private South audioSouth;

    private South videoSouth;


    /**
     * @param workbench
     */
    public FileEditor(WorkbenchController workbench, String id) {
        super(workbench, id);
        mkdirForNoExists(new AppServiceFileUtils().imgDirPath_app);
        mkdirForNoExists(new AppServiceFileUtils().cssDirPath_app);
        mkdirForNoExists(new AppServiceFileUtils().jsDirPath_app);
        mkdirForNoExists(new AppServiceFileUtils().audioDirPath_app);
        mkdirForNoExists(new AppServiceFileUtils().videoDirPath_app);
    }

    @Override
    public void create(Object... args) {
        Idspace is = createPanel(Labels.getLabel("menu.appfile"), "~./images/explorer.gif", "~./include/editor/workbench/file.zul");
        for (Component comp : is.getFellows()) {
            if (comp.getId().equals("file_tabbox_main")) {
                tabbox = (Tabbox) comp;
            } else if (comp.getId().equals("file_div_image_imgList")) {
                center = (Div) comp;
            } else if (comp.getId().equals("file_iframe_audio_play")) {
                iframe_audio = (Iframe) comp;
            } else if (comp.getId().equals("file_iframe_video_play")) {
                iframe_video = (Iframe) comp;
            } else if (comp.getId().equals("file_listbox_audio_list")) {
                audioListbox = (Listbox) comp;
            } else if (comp.getId().equals("file_listbox_video_list")) {
                videoListbox = (Listbox) comp;
            } else if (comp.getId().equals("file_listbox_css_list")) {
                cssListbox = (Listbox) comp;
            } else if (comp.getId().equals("file_listbox_js_list")) {
                jsListbox = (Listbox) comp;
            } else if (comp.getId().equals("file_listbox_image_hist_list")) {
                imgHistory = (Listbox) comp;
                imgHistory.setPageSize(5);
                imgHistory.getPaginal().setPageSize(5);
                imgHistory.addEventListener(Events.ON_SELECT, this);
            } else if (comp.getId().equals("file_listbox_css_hist_list")) {
                cssHistory = (Listbox) comp;
                cssHistory.setPageSize(5);
                cssHistory.getPaginal().setPageSize(5);
                cssHistory.addEventListener(Events.ON_SELECT, this);
            } else if (comp.getId().equals("file_listbox_js_hist_list")) {
                jsHistory = (Listbox) comp;
                jsHistory.setPageSize(5);
                jsHistory.getPaginal().setPageSize(5);
                jsHistory.addEventListener(Events.ON_SELECT, this);
            } else if (comp.getId().equals("file_listbox_audio_hist_list")) {
                audioHistory = (Listbox) comp;
                audioHistory.setPageSize(5);
                audioHistory.getPaginal().setPageSize(5);
                audioHistory.addEventListener(Events.ON_SELECT, this);
            } else if (comp.getId().equals("file_listbox_video_hist_list")) {
                videoHistory = (Listbox) comp;
                videoHistory.setPageSize(5);
                videoHistory.getPaginal().setPageSize(5);
                videoHistory.addEventListener(Events.ON_SELECT, this);
            } else if (comp.getId().equals("file_button_image_upload")) {
                upload_img = (Button) comp;
                upload_img.addEventListener(Events.ON_UPLOAD, this);
            } else if (comp.getId().equals("file_button_audio_upload")) {
                upload_audio = (Button) comp;
                upload_audio.addEventListener(Events.ON_UPLOAD, this);
            } else if (comp.getId().equals("file_button_video_upload")) {
                upload_video = (Button) comp;
                upload_video.addEventListener(Events.ON_UPLOAD, this);
            } else if (comp.getId().equals("file_button_css_upload")) {
                upload_css = (Button) comp;
                upload_css.addEventListener(Events.ON_UPLOAD, this);
            } else if (comp.getId().equals("file_button_js_upload")) {
                upload_js = (Button) comp;
                upload_js.addEventListener(Events.ON_UPLOAD, this);
            } else if (comp.getId().equals("file_button_image_imgHist")) {
                btnImgHist = (Button) comp;
                btnImgHist.addEventListener(Events.ON_CLICK, this);
            } else if (comp.getId().equals("file_button_image_imgHist_Ref")) {
                btnImgHistRef = (Button) comp;
                btnImgHistRef.addEventListener(Events.ON_CLICK, this);
            } else if (comp.getId().equals("file_button_image_imgHist_revert")) {
                btnImgRevert = (Button) comp;
                btnImgRevert.addEventListener(Events.ON_CLICK, this);
            } else if (comp.getId().equals("file_south_image_imgHist")) {
                imgSouth = (South) comp;
            } else if (comp.getId().equals("file_button_css_cssHist")) {
                btnCssHist = (Button) comp;
                btnCssHist.addEventListener(Events.ON_CLICK, this);
            } else if (comp.getId().equals("file_button_css_cssHist_ref")) {
                btnCssHistRef = (Button) comp;
                btnCssHistRef.addEventListener(Events.ON_CLICK, this);
            } else if (comp.getId().equals("file_button_css_cssHist_revert")) {
                btnCssRevert = (Button) comp;
                btnCssRevert.addEventListener(Events.ON_CLICK, this);
            } else if (comp.getId().equals("file_south_css_cssHist")) {
                cssSouth = (South) comp;
            } else if (comp.getId().equals("file_button_js_jsHist")) {
                btnJsHist = (Button) comp;
                btnJsHist.addEventListener(Events.ON_CLICK, this);
            } else if (comp.getId().equals("file_button_js_jsHist_ref")) {
                btnJsHistRef = (Button) comp;
                btnJsHistRef.addEventListener(Events.ON_CLICK, this);
            } else if (comp.getId().equals("file_button_js_jsHis_revert")) {
                btnJsRevert = (Button) comp;
                btnJsRevert.addEventListener(Events.ON_CLICK, this);
            } else if (comp.getId().equals("file_south_js_jsHist")) {
                jsSouth = (South) comp;
            } else if (comp.getId().equals("file_button_audio_audioHist")) {
                btnAudioHist = (Button) comp;
                btnAudioHist.addEventListener(Events.ON_CLICK, this);
            } else if (comp.getId().equals("file_button_audio_audioHist_ref")) {
                btnAudioHistRef = (Button) comp;
                btnAudioHistRef.addEventListener(Events.ON_CLICK, this);
            } else if (comp.getId().equals("file_button_audio_audioHist_revert")) {
                btnAudioRevert = (Button) comp;
                btnAudioRevert.addEventListener(Events.ON_CLICK, this);
            } else if (comp.getId().equals("file_south_audio_audioHist")) {
                audioSouth = (South) comp;
            } else if (comp.getId().equals("file_button_video_videoHist")) {
                btnVideoHist = (Button) comp;
                btnVideoHist.addEventListener(Events.ON_CLICK, this);
            } else if (comp.getId().equals("file_button_video_videoHist_ref")) {
                btnVideoHistRef = (Button) comp;
                btnVideoHistRef.addEventListener(Events.ON_CLICK, this);
            } else if (comp.getId().equals("file_button_video_videoHist_revert")) {
                btnVideoRevert = (Button) comp;
                btnVideoRevert.addEventListener(Events.ON_CLICK, this);
            } else if (comp.getId().equals("file_south_video_videoHist")) {
                videoSouth = (South) comp;
            } else if (comp.getId().equals("file_image_image_pics")) {
                pics = (Image) comp;
            } else if (comp.getId().equals("file_image_div_imgHist_frame")) {
                imgFrame = (Div) comp;
            } else if (comp.getId().equals("file_image_image_imgHist_preView")) {
                preView = (Image) comp;
            } else if (comp.getId().equals("file_menu_download")) {
                menu = (Menupopup) comp;
                List<Menuitem> a = menu.getChildren();
                for (Menuitem menuitem : a) {
                    menuitem.addEventListener(Events.ON_CLICK, this);
                }
                menu.addEventListener(Events.ON_OPEN, this);
            } else if (comp.getId().equals("dropuploadPic")) {
                Dropupload dropupload = (Dropupload) comp;
                dropupload.addEventListener(Events.ON_UPLOAD, this);
            } else if (comp.getId().equals("dropuploadVideo")) {
                Dropupload dropupload = (Dropupload) comp;
                dropupload.addEventListener(Events.ON_UPLOAD, this);
            } else if (comp.getId().equals("dropuploadAudio")) {
                Dropupload dropupload = (Dropupload) comp;
                dropupload.addEventListener(Events.ON_UPLOAD, this);
            } else if (comp.getId().equals("dropuploadCSS")) {
                Dropupload dropupload = (Dropupload) comp;
                dropupload.addEventListener(Events.ON_UPLOAD, this);
            } else if (comp.getId().equals("dropuploadJS")) {
                Dropupload dropupload = (Dropupload) comp;
                dropupload.addEventListener(Events.ON_UPLOAD, this);
            }
        }
        audioListbox.setContext(menu.getId());
        videoListbox.setContext(menu.getId());
        cssListbox.setContext(menu.getId());
        jsListbox.setContext(menu.getId());
        refreshImageGrid();
        refreshAudioListbox();
        refreshVideoListbox();
        refreshCssListbox();
        refreshJsListbox();
        /*Clients.showBusy(Labels.getLabel("message.long.operation"));*/

        //将projectID传入servlet，获取apps路径进行渲染
        center.getDesktop().getSession().setAttribute("projectName", Contexts.getProject().getId());
    }

    private void refreshImageGrid() {
        center.getChildren().clear();
        List<String> fileName = Arrays.asList(new File(new AppServiceFileUtils().imgDirPath_app).list());
        Grid grid = new Grid();
        grid.setHflex("1");
        grid.setVflex("1");
        grid.setSclass("epview-icons");
        grid.setMold("paging");
        grid.setPageSize(6);
        grid.appendChild(new Rows());
        Row row = null;
        for (int i = 0; i < fileName.size(); i++) {
            if (i % 5 == 0)
                row = new Row();
            row.setStyle("height: 200px;");
            Image a = new Image();
            a.setStyle("padding:5px;max-height: 160px;max-width: 220px;");
            a.setTooltiptext(fileName.get(i));
//          a.setTooltiptext("/apps/" + Contexts.getProject().getId() + "/css/" + fileName.get(i));
            if (!FileUtil.isContainChinese(fileName.get(i))) {
                a.setSrc("template/public/img/" + fileName.get(i));
            } else {
                try {
                    //setContent加载比较慢
                    a.setContent(new AImage(fileName.get(i), new FileInputStream(new AppServiceFileUtils().imgDirPath_app + File.separator + fileName.get(i))));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            a.setContext(menu.getId());
            row.appendChild(a);
            grid.getRows().appendChild(row);
        }
        center.appendChild(grid);
    }

    private void refreshAudioListbox() {
        audioListbox.getItems().clear();
        List<String> fileName = Arrays.asList(new File(new AppServiceFileUtils().audioDirPath_app).list());
        for (int i = 0; i < fileName.size(); i++) {
            String name = fileName.get(i);
            Listitem row = new Listitem();
            row.setValue(new AppServiceFileUtils().audioDirPath_app + File.separator + fileName.get(i));
            row.appendChild(new Listcell(i + ""));
            row.appendChild(new Listcell(name));
            row.setParent(this.audioListbox);
            row.setTooltiptext(fileName.get(i));
            row.addEventListener(Events.ON_DOUBLE_CLICK, new EventListener<Event>() {
                @Override
                public void onEvent(Event event) throws Exception {
                    Listitem row = (Listitem) event.getTarget();
                    String filePath = row.getValue() + "";
                    String name = filePath.substring(filePath.lastIndexOf("\\") + 1);
                    String suffix = filePath.substring(filePath.lastIndexOf(".") + 1);
                    iframe_audio.setContent(new AMedia(name,null,"audio/" + suffix,new File(row.getValue() + ""),  null));
                }
            });
        }
    }

    private void refreshVideoListbox() {
        videoListbox.getItems().clear();
        List<String> fileName = Arrays.asList(new File(new AppServiceFileUtils().videoDirPath_app).list());
        for (int i = 0; i < fileName.size(); i++) {
            String name = fileName.get(i);
            Listitem row = new Listitem();
            row.setValue(new AppServiceFileUtils().videoDirPath_app + File.separator + fileName.get(i));
            row.appendChild(new Listcell(i + ""));
            row.appendChild(new Listcell(name));
            row.setParent(this.videoListbox);
            row.setTooltiptext(fileName.get(i));
            row.addEventListener(Events.ON_DOUBLE_CLICK, new EventListener<Event>() {
                @Override
                public void onEvent(Event event) throws Exception {
                    Listitem row = (Listitem) event.getTarget();
                    String filePath = row.getValue() + "";
                    String name = filePath.substring(filePath.lastIndexOf("\\") + 1);
                    String suffix = filePath.substring(filePath.lastIndexOf(".") + 1);
                    iframe_video.setContent(new AMedia(name,null,"video/" + suffix,new File(row.getValue() + ""),  null));
                }
            });
        }
    }

    private void refreshCssListbox() {
        cssListbox.getItems().clear();
        List<String> fileName = Arrays.asList(new File(new AppServiceFileUtils().cssDirPath_app).list());
        for (int i = 0; i < fileName.size(); i++) {
            String name = fileName.get(i);
            Listitem row = new Listitem();
            row.setValue(new AppServiceFileUtils().cssDirPath_app + File.separator + fileName.get(i));
            row.appendChild(new Listcell(i + ""));
            row.appendChild(new Listcell(name));
            row.setParent(this.cssListbox);
            row.setTooltiptext(fileName.get(i));
            row.addEventListener(Events.ON_DOUBLE_CLICK, this);
        }
    }

    private void refreshJsListbox() {
        jsListbox.getItems().clear();
        List<String> fileName = Arrays.asList(new File(new AppServiceFileUtils().jsDirPath_app).list());
        for (int i = 0; i < fileName.size(); i++) {
            String name = fileName.get(i);
            Listitem row = new Listitem();
            row.setValue(new AppServiceFileUtils().jsDirPath_app + File.separator + fileName.get(i));
            row.appendChild(new Listcell(i + ""));
            row.appendChild(new Listcell(name));
            row.setParent(this.jsListbox);
            row.setTooltiptext(fileName.get(i));
            row.addEventListener(Events.ON_DOUBLE_CLICK, this);
        }
    }

    private void refreshHistory(String type, Listbox histList) {
        histList.getItems().clear();
        UploadHistVo uploadHistVo = new UploadHistVo();
        uploadHistVo.setType(type);
        uploadHistVo.setProjectName(Contexts.getProject().getName());
        List<UploadHistVo> histories = readUploadHist(uploadHistVo);
        for (UploadHistVo vo : histories) {
            Listitem li = new Listitem();
            li.appendChild(new Listcell(vo.getId() + ""));
            li.appendChild(new Listcell(vo.getFileName()));
            li.appendChild(new Listcell(vo.getContentType()));
            li.appendChild(new Listcell(vo.getUploadUser()));
            li.appendChild(new Listcell(vo.getPackName()));
            li.appendChild(new Listcell(vo.getCreateDate().toString()));
            li.appendChild(new Listcell(vo.getType()));
            li.setValue(vo);
            li.setParent(histList);
        }
    }

    @Override
    public void dispatch(Event event) {
        if (event.getName().equals(Events.ON_OPEN)) {
            OpenEvent evt = (OpenEvent) event;
            if (event.getTarget().getId().equals("file_menu_download")) {
                if (evt.isOpen()) {
                    selectComp = evt.getReference();
                }
            }
        }
        if (event.getName().equals(Events.ON_CLICK)) {
            if (event.getTarget() instanceof Menuitem) {
                Menuitem menuitem = (Menuitem) event.getTarget();
                if (menuitem.getLabel().equals(Labels.getLabel("button.download"))) {
                    try {
                        if (selectComp instanceof Image) {
                            Image selectImage = (Image) selectComp;
                            if (selectImage.getSrc() != null) {
                                String path = new AppServiceFileUtils().templatePath_app+selectImage.getSrc().substring(selectImage.getSrc().indexOf("/")+1);
                                Filedownload.save(new File(path), null);
                            }
                            else {
                                Filedownload.save(selectImage.getContent(), null);
                            }
                        }
                        if (selectComp instanceof Listbox) {
                            Listbox selectListbox = (Listbox) selectComp;
                            if (selectListbox.getSelectedItem() == null) {
                                Messagebox.show(Labels.getLabel("editor.file.revert.warning"), "Error", Messagebox.OK, Messagebox.ERROR);
                                return;
                            }
                            Filedownload.save(new File(selectListbox.getSelectedItem().getValue() + ""), null);
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }else if(menuitem.getLabel().equals(Labels.getLabel("button.delete"))) {
                    if (selectComp instanceof Image) {
                        Image selectImage = (Image) selectComp;
                        if (selectImage.getSrc() != null) {
                            String imgPath = new AppServiceFileUtils().templatePath_app+selectImage.getSrc().substring(9);
                            FileUtil.deleteDir(new File(imgPath));
                        }
                        else {
                            FileUtil.deleteDir(new File(new AppServiceFileUtils().imgDirPath_app+(selectImage.getContent().getName())));
                        }
                    }
                    if (selectComp instanceof Listbox) {
                        Listbox selectListbox = (Listbox) selectComp;
                        if (selectListbox.getSelectedItem() == null) {
                            Messagebox.show(Labels.getLabel("editor.file.revert.warning"), "Error", Messagebox.OK, Messagebox.ERROR);
                            return;
                        }
                        String filePath = selectListbox.getSelectedItem().getValue()+"";
                        String filename = filePath.substring(filePath.lastIndexOf("\\") + 1);
                        if(null!=iframe_video.getContent()&&(iframe_video.getContent().getName()).equals(filename)){
                            iframe_video.setContent(null);
                        }
                        if(null!=iframe_audio.getContent()&&(iframe_audio.getContent().getName()).equals(filename)){
                            iframe_audio.setContent(null);
                        }
                        FileUtil.deleteDir(new File(filePath));
                    }
                    refreshImageGrid();
                    refreshAudioListbox();
                    refreshVideoListbox();
                    refreshCssListbox();
                    refreshJsListbox();
                    refreshImageGrid();
                    refreshAudioListbox();
                    refreshVideoListbox();
                    refreshCssListbox();
                    refreshJsListbox();
                }
            }

            /*-------------------------------------img--------------------------------*/
            if (event.getTarget().getId().equals("file_button_image_imgHist")) {//显示图片历史列表
                if (!imgSouth.isVisible()) {
                    refreshHistory(ServiceFileUtil.MediaType.MEDIA_TYPE_IMG.getName(), imgHistory);
                    imgSouth.setVisible(true);
                    imgFrame.setVisible(true);
                    preView.setVisible(false);
                }
            }
            if (event.getTarget().getId().equals("file_button_image_imgHist_Ref")) {//刷新图片历史列表
                refreshHistory(ServiceFileUtil.MediaType.MEDIA_TYPE_IMG.getName(), imgHistory);
                imgFrame.setVisible(true);
                preView.setVisible(false);
            }
            if (event.getTarget().getId().equals("file_button_image_imgHist_revert")) {//图片历史回滚
                revertFile(imgHistory);
            }
            /*-------------------------------------img--------------------------------*/
            /*-------------------------------------css--------------------------------*/
            if (event.getTarget().getId().equals("file_button_css_cssHist")) {//显示CSS历史列表
                if (!cssSouth.isVisible()) {
                    refreshHistory(ServiceFileUtil.MediaType.MEDIA_TYPE_CSS.getName(), cssHistory);
                    cssSouth.setVisible(true);
                }
            }
            if (event.getTarget().getId().equals("file_button_css_cssHist_ref")) {//刷新CSS历史列表
                refreshHistory(ServiceFileUtil.MediaType.MEDIA_TYPE_CSS.getName(), cssHistory);
            }
            if (event.getTarget().getId().equals("file_button_css_cssHist_revert")) {//CSS历史回滚
                revertFile(cssHistory);
            }
            /*-------------------------------------css--------------------------------*/
            /*-------------------------------------js--------------------------------*/
            if (event.getTarget().getId().equals("file_button_js_jsHist")) {//显示JS历史列表
                if (!jsSouth.isVisible()) {
                    refreshHistory(ServiceFileUtil.MediaType.MEDIA_TYPE_JS.getName(), jsHistory);
                    jsSouth.setVisible(true);
                }
            }
            if (event.getTarget().getId().equals("file_button_js_jsHist_ref")) {//刷新JS历史列表
                refreshHistory(ServiceFileUtil.MediaType.MEDIA_TYPE_JS.getName(), jsHistory);
            }
            if (event.getTarget().getId().equals("file_button_js_jsHis_revert")) {//JS历史回滚
                revertFile(jsHistory);
            }
            /*-------------------------------------js--------------------------------*/
            /*-------------------------------------audio--------------------------------*/
            if (event.getTarget().getId().equals("file_button_audio_audioHist")) {//显示音频历史列表
                if (!audioSouth.isVisible()) {
                    refreshHistory(ServiceFileUtil.MediaType.MEDIA_TYPE_AUDIO.getName(), audioHistory);
                    audioSouth.setVisible(true);
                }
            }
            if (event.getTarget().getId().equals("file_button_audio_audioHist_ref")) {//刷新音频历史列表
                refreshHistory(ServiceFileUtil.MediaType.MEDIA_TYPE_AUDIO.getName(), audioHistory);
            }
            if (event.getTarget().getId().equals("file_button_audio_audioHist_revert")) {//音频历史回滚
                revertFile(audioHistory);
            }
            /*-------------------------------------audio--------------------------------*/
            /*-------------------------------------video--------------------------------*/
            if (event.getTarget().getId().equals("file_button_video_videoHist")) {//显示视频历史列表
                if (!videoSouth.isVisible()) {
                    refreshHistory(ServiceFileUtil.MediaType.MEDIA_TYPE_VIDEO.getName(), videoHistory);
                    videoSouth.setVisible(true);
                }
            }
            if (event.getTarget().getId().equals("file_button_video_videoHist_ref")) {//刷新视频历史列表
                refreshHistory(ServiceFileUtil.MediaType.MEDIA_TYPE_VIDEO.getName(), videoHistory);
            }
            if (event.getTarget().getId().equals("file_button_video_videoHist_revert")) {//视频历史回滚
                revertFile(videoHistory);
            }
            /*-------------------------------------video--------------------------------*/
        }
        if (event.getName().equals(Events.ON_UPLOAD)) {
            UploadEvent evt = (UploadEvent) event;
            org.zkoss.util.media.Media media = evt.getMedia();
            if (evt.getTarget().getId().equals("file_button_image_upload") || evt.getTarget().getId().equals("dropuploadPic")) {
                if (media instanceof org.zkoss.image.Image) {
                    org.zkoss.image.Image img = (org.zkoss.image.Image) media;
                    pics.setWidth("");
                    pics.setHeight("");
                    pics.setStyle("border:3px dashed #e6e6e6;border-radius:10px;display: inline;justify-content:center;align-items:Center;max-height: 250px;max-width: 250px;");
                    pics.setContent(img);
                    copyMediaToFile(new AppServiceFileUtils().imgDirPath_app, media);
                    writeUploadHist(media, ServiceFileUtil.MediaType.MEDIA_TYPE_IMG.getName());
                    refreshImageGrid();
                } else {
                    //Messagebox.show("Not an image: " + media, "Error", Messagebox.OK, Messagebox.ERROR);
                    WebUtils.showError(Labels.getLabel("file.upload.error"));
                }
            }
            if (evt.getTarget().getId().equals("file_button_audio_upload") || evt.getTarget().getId().equals("dropuploadAudio")) {
                if (media instanceof org.zkoss.sound.Audio) {
                    iframe_audio.setContent(media);
                    copyMediaToFile(new AppServiceFileUtils().audioDirPath_app, media);
                    writeUploadHist(media, ServiceFileUtil.MediaType.MEDIA_TYPE_AUDIO.getName());
                    refreshAudioListbox();
                } else if (media != null) {
                    //Messagebox.show("Not an audio: " + media, "Error", Messagebox.OK, Messagebox.ERROR);
                    WebUtils.showError(Labels.getLabel("file.upload.error"));
                }
            }
            if (evt.getTarget().getId().equals("file_button_video_upload") || evt.getTarget().getId().equals("dropuploadVideo")) {
                if (media instanceof org.zkoss.video.Video) {
                    iframe_video.setContent(media);
                    copyMediaToFile(new AppServiceFileUtils().videoDirPath_app, media);
                    writeUploadHist(media, ServiceFileUtil.MediaType.MEDIA_TYPE_VIDEO.getName());
                    refreshVideoListbox();
                } else if (media != null) {
                    //Messagebox.show("Not an video: " + media, "Error", Messagebox.OK, Messagebox.ERROR);
                    WebUtils.showError(Labels.getLabel("file.upload.error"));
                }
            }
            if (evt.getTarget().getId().equals("file_button_css_upload") || evt.getTarget().getId().equals("dropuploadCSS")) {
                if ("text/css".equals(media.getContentType())) {
                    copyMediaToFile(new AppServiceFileUtils().cssDirPath_app, media);
                    writeUploadHist(media, ServiceFileUtil.MediaType.MEDIA_TYPE_CSS.getName());
                    refreshCssListbox();
                } else if (media != null) {
                    //Messagebox.show("Not an css: " + media, "Error", Messagebox.OK, Messagebox.ERROR);
                    WebUtils.showError(Labels.getLabel("file.upload.error"));
                }
            }
            if (evt.getTarget().getId().equals("file_button_js_upload") || evt.getTarget().getId().equals("dropuploadJS")) {
                if ("text/javascript".equals(media.getContentType())) {
                    copyMediaToFile(new AppServiceFileUtils().jsDirPath_app, media);
                    writeUploadHist(media, ServiceFileUtil.MediaType.MEDIA_TYPE_JS.getName());
                    refreshJsListbox();
                } else if (media != null) {
                    //Messagebox.show("Not an js: " + media, "Error", Messagebox.OK, Messagebox.ERROR);
                    WebUtils.showError(Labels.getLabel("file.upload.error"));
                }
            }
        }
        if (event.getName().equals(Events.ON_SELECT)) {
            if (event.getTarget().getId().equals("file_listbox_image_hist_list")) {
                UploadHistVo vo = imgHistory.getSelectedItem().getValue();
                if (vo != null) {
                    try {
                        imgFrame.setVisible(false);
                        preView.setContent(new AImage(vo.getFileName(), decoder.decodeBuffer(vo.getUploadData())));
                        preView.setStyle("border:1.2px solid #DCDCDC;display: flex;justify-content:center;align-items:Center;max-height: 200px;max-width: 200px;");
                        preView.setVisible(true);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if (event.getName().equals(Events.ON_DOUBLE_CLICK) && event.getTarget() instanceof Listitem) {
            Listitem selectedItem = (Listitem) event.getTarget();
            MediaFileVo vo = new MediaFileVo();
            vo.setType(ServiceFileUtil.MediaType.MEDIA_TYPE_CSS.getName());
            vo.setPath((String) selectedItem.getValue());
            AbstractView.createFileView(new ComponentCallback(tabbox, Labels.getLabel("editor.import.file.info")),
                    vo).doOverlapped();
        }
    }

    private void copyMediaToFile(String dirPath_app, Media media) {
        try {
            String mediaPath_apps = dirPath_app + File.separator + media.getName();
            if ("text/css".equals(media.getContentType())) {
                byte[] bytes = null;
                try {
                    bytes = media.getByteData();
                } catch (IllegalStateException e) {
                    bytes = media.getStringData().getBytes();
                }
                FileUtils.copyInputStreamToFile(new ByteArrayInputStream(bytes), new File(mediaPath_apps));
            } else if ("text/javascript".equals(media.getContentType())) {
                try {
                    FileUtils.copyInputStreamToFile(new ReaderInputStream(media.getReaderData()), new File(mediaPath_apps));
                } catch (IllegalStateException e) {
                    FileUtils.copyInputStreamToFile(new ByteArrayInputStream(media.getByteData()), new File(mediaPath_apps));
                }
            } else {
                FileUtils.copyInputStreamToFile(media.getStreamData(), new File(mediaPath_apps));
            }
            WebUtils.showSuccess(Labels.getLabel("editor.file.upload"));
        } catch (IOException e) {
            WebUtils.showError(Labels.getLabel("message.error", new String[]{Labels.getLabel("editor.file.upload")}));
            e.printStackTrace();
        }
    }

    //回滚文件
    private void revertFile(Listbox histListbox) {
        try {
            if (histListbox.getSelectedItem() == null) {
                Messagebox.show(Labels.getLabel("editor.file.revert.warning"), "Error", Messagebox.OK, Messagebox.ERROR);
                return;
            }
            UploadHistVo vo = histListbox.getSelectedItem().getValue();
            if (vo.getType().equals(ServiceFileUtil.MediaType.MEDIA_TYPE_IMG.getName())) {
                copyMediaToFile(new AppServiceFileUtils().imgDirPath_app, new AImage(vo.getFileName(), decoder.decodeBuffer(vo.getUploadData())));
                refreshImageGrid();
            } else if (vo.getType().equals(ServiceFileUtil.MediaType.MEDIA_TYPE_CSS.getName())) {
                copyMediaToFile(new AppServiceFileUtils().cssDirPath_app, new AMedia(vo.getFileName(), null, vo.getContentType(), decoder.decodeBuffer(vo.getUploadData())));
                refreshCssListbox();
            } else if (vo.getType().equals(ServiceFileUtil.MediaType.MEDIA_TYPE_JS.getName())) {
                copyMediaToFile(new AppServiceFileUtils().jsDirPath_app, new AMedia(vo.getFileName(), null, vo.getContentType(), decoder.decodeBuffer(vo.getUploadData())));
                refreshJsListbox();
            } else if (vo.getType().equals(ServiceFileUtil.MediaType.MEDIA_TYPE_AUDIO.getName())) {
                copyMediaToFile(new AppServiceFileUtils().audioDirPath_app, new AMedia(vo.getFileName(), null, vo.getContentType(), decoder.decodeBuffer(vo.getUploadData())));
                refreshAudioListbox();
            } else if (vo.getType().equals(ServiceFileUtil.MediaType.MEDIA_TYPE_VIDEO.getName())) {
                copyMediaToFile(new AppServiceFileUtils().videoDirPath_app, new AMedia(vo.getFileName(), null, vo.getContentType(), decoder.decodeBuffer(vo.getUploadData())));
                refreshVideoListbox();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //数据库增加一条上传历史记录
    private void writeUploadHist(Media media, String type) {
        if ("text/css".equals(media.getContentType())) {
            StudioApp.execute(new SetUploadHistCmd(new UploadHistVo(media.getName(), encoder.encode(media.getStringData().getBytes()), type, media.getContentType(), media.getName(), Contexts.getProject().getName(), Contexts.getUser().getName())));
        } else if ("text/javascript".equals(media.getContentType())) {
            try {
                StudioApp.execute(new SetUploadHistCmd(new UploadHistVo(media.getName(), encoder.encode(IOUtils.toByteArray(media.getReaderData())), type, media.getContentType(), media.getName(), Contexts.getProject().getName(), Contexts.getUser().getName())));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if ("video".equals(type)) {
            try {
                StudioApp.execute(new SetUploadHistCmd(new UploadHistVo(media.getName(), encoder.encode(IOUtils.toByteArray(media.getStreamData())), type, media.getContentType(), media.getName(), Contexts.getProject().getName(), Contexts.getUser().getName())));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            StudioApp.execute(new SetUploadHistCmd(new UploadHistVo(media.getName(), encoder.encode(media.getByteData()), type, media.getContentType(), media.getName(), Contexts.getProject().getName(), Contexts.getUser().getName())));
        }
    }

    //查询上传历史记录
    private List<UploadHistVo> readUploadHist(UploadHistVo vo) {
        return StudioApp.execute(new GetUploadHistCmd(vo));
    }

    //文件目录不存在则创建
    private void mkdirForNoExists(String dirPath) {
        if (!new File(dirPath).exists()) {
            try {
                FileUtils.forceMkdir(new File(dirPath));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
